 //
//  HCUpdateManager.m
//  HeroCar
//
//  Created by rui on 1/10/15.
//  Copyright (c) 2015 SZZCIT. All rights reserved.
//

#import "HCUpdateManager.h"
#import "ASIFormDataRequest.h"
#import "NetworkCheck.h"
#import "AppDelegate.h"

static NSString *AppDownloadAddress = @"itms-services://?action=download-manifest&url=https://xstore.saicmotor.com/audit/Audit.plist";

@interface HCUpdateManager ()

@property(nonatomic,copy)NSString *appAdrress;
@end


@implementation HCUpdateManager

- (id)init {
	self = [super init];
	if (self) {
		self.appAdrress = AppDownloadAddress;
	}
	return self;
}

+ (instancetype)sharedInstance {
	static HCUpdateManager * _instance = nil;
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		_instance = [[HCUpdateManager alloc]init];
	});
	return _instance;
}

- (void)startingDetecting {
	
	NSString *urlLogin=[NSString stringWithFormat:@"%@%@",__URL__,@"GetNewVersion"];
	
	NSURL *postURL=[NSURL URLWithString:urlLogin];
	ASIFormDataRequest *asiFDR=[[ASIFormDataRequest alloc] initWithURL:postURL];
	
//	[asiFDR setPostValue:secret_Keys forKey:@"strSecretKeys"];
	[asiFDR setPostValue:@"ios" forKey:@"strDeviceType"];
	[asiFDR setDelegate:self];
	[asiFDR setDidFinishSelector:@selector(requestFinishedUserList:)];
	[asiFDR setDidFailSelector:@selector(requestFailedUserList:)];
	[asiFDR startAsynchronous];
	
//	[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
}

- (void)requestFinishedUserList:(ASIHTTPRequest *)sender {
	
//	[MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
	
//	NSString *responseString = sender.responseString;
//	
//	NSString *strJSON=[responseString substringFromIndex:[responseString rangeOfString:@">{"].location+1 ];
//	NSString *strResult=[strJSON substringToIndex:[strJSON rangeOfString:@"}<"].location+1 ];
    
    NSString *strResult = sender.responseString;
	
	if (![strResult isEqualToString:@"{}"])
	{
		NSString *str=[NSString stringWithFormat:@"%@",strResult];
		
		str=[str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
		str=[str stringByReplacingOccurrencesOfString:@"\t" withString:@""];
		str=[str stringByReplacingOccurrencesOfString:@"\r" withString:@""];
		
		NSData *data=[str dataUsingEncoding: NSUTF8StringEncoding];

		NSDictionary *info = [NSJSONSerialization JSONObjectWithData:data
														 options:NSJSONReadingMutableContainers
														   error:nil];
		
		
		NSString *remoteVersion = [info valueForKeyPath:@"data.version"];
		self.appAdrress = [info valueForKeyPath:@"data.version_address"]; //测试注释这行代码
		
		NSString *current = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
		
		if (remoteVersion.floatValue > current.floatValue) {
			NSString *title = [NSString stringWithFormat:@"您当前版本为:%@,最新版本为:%@",current,remoteVersion];
			[self alertSuccessWithTitle:title];
		}
		else {
			[self alertFaild];
		}
	}
	else {
		[self alertFaild];
	}
}

- (void)requestFailedUserList:(id)sender {
//	[MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
//	[self alertFaild];
//    [NetworkCheck checkNetwork];
}

- (void)alertFaild {
	
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@" " message:@"暂未发现更新"
							   delegate:nil
					  cancelButtonTitle:@"知道了"
					  otherButtonTitles:nil,nil];
	[alert show];
}

- (void)alertSuccessWithTitle:(NSString *)title {
	
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"发现新版本" message:title
												   delegate:self
										  cancelButtonTitle:@"取消"
										  otherButtonTitles:@"更新",nil];
	[alert show];
	
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
	if (buttonIndex == 1) {
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.appAdrress]];
        
        [self exitApplication ];
	}
}

- (void)exitApplication {
    
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    UIWindow *window = app.window;
    
    [UIView animateWithDuration:1.0f animations:^{
        window.alpha = 0;
        window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
    } completion:^(BOOL finished) {
        exit(0);
    }];
    //exit(0);
    
}


- (void)startingDetectingWithoutLoading {
    NSString *urlLogin=[NSString stringWithFormat:@"%@%@",__URL__,@"GetNewVersion"];
    
    NSURL *postURL=[NSURL URLWithString:urlLogin];
    ASIFormDataRequest *asiFDR=[[ASIFormDataRequest alloc] initWithURL:postURL];
    
//    [asiFDR setPostValue:secret_Keys forKey:@"strSecretKeys"];
    [asiFDR setPostValue:@"ios" forKey:@"strDeviceType"];
    [asiFDR setDelegate:self];
    [asiFDR setDidFinishSelector:@selector(requestFinishedWithoutLoading:)];
    [asiFDR setDidFailSelector:@selector(requestFailedWithoutLoading:)];
    [asiFDR startAsynchronous];
    
    //    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
}

- (void)requestFinishedWithoutLoading:(ASIHTTPRequest *)sender {
    
//    [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
    
    NSString *responseString = sender.responseString;

//    NSString *strJSON=[responseString substringFromIndex:[responseString rangeOfString:@">{"].location+1 ];
//    NSString *strResult=[strJSON substringToIndex:[strJSON rangeOfString:@"}<"].location+1 ];
    
//    NSString *strJSON=[responseString substringFromIndex:[responseString rangeOfString:@"/\">"].location+3 ];
//    NSString *strResult=[strJSON substringToIndex:[strJSON rangeOfString:@"</"].location ];
    
//    NSString *test=@"{\"code\":\"123\"}";
//    
//    test=[JoDes encode:test key:@"CEHrDooxWHCWtfeSxvDvgqZZ"];
//    
//    NSLog(@"%@",test);
//    
//    test=[JoDes decode:test key:@"CEHrDooxWHCWtfeSxvDvgqZZ"];
//    
//    NSLog(@"%@",test);
//    
//    NSString *key=[JoDes md5:@"ausdifa4"];
//    
//    key=[key substringToIndex:8];
    
//    NSString *strJSON=[responseString substringFromIndex:[responseString rangeOfString:@"/\">"].location+3 ];
//    NSString *strResult=[strJSON substringToIndex:[strJSON rangeOfString:@"</"].location ];
//    
//    strResult=[JoDes decode:strResult key:@"ausdifa4"];
    
    NSString *strResult = sender.responseString;
    
    if (![strResult isEqualToString:@"{}"])
    {
        NSString *str=[NSString stringWithFormat:@"%@",strResult];
        
        str=[str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        str=[str stringByReplacingOccurrencesOfString:@"\t" withString:@""];
        str=[str stringByReplacingOccurrencesOfString:@"\r" withString:@""];
        
        NSData *data=[str dataUsingEncoding: NSUTF8StringEncoding];
        
        NSDictionary *info = [NSJSONSerialization JSONObjectWithData:data
                                                             options:NSJSONReadingMutableContainers
                                                               error:nil];
        
        
        NSString *remoteVersion = [info valueForKeyPath:@"data.version"];
        self.appAdrress = [info valueForKeyPath:@"data.version_address"]; //测试注释这行代码
        
        NSString *current = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        
        if (remoteVersion.floatValue > current.floatValue) {
            NSString *title = [NSString stringWithFormat:@"您当前版本为:%@,最新版本为:%@",current,remoteVersion];
            [self alertSuccessWithTitle:title];
        }
        else {
//            [self alertFaild];
        }
    }
    else {
//        [self alertFaild];
    }
}

- (void)requestFailedWithoutLoading:(id)sender {
//    [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
//    [self alertFaild];

}

@end
